/**
 * 
 */
package com.baijia.tianxiao.connect.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baijia.tianxiao.connect.config.Constants;
import com.baijia.tianxiao.connect.enums.CCBizName;
import com.baijia.tianxiao.connect.enums.MessageBizDomain;
import com.baijia.tianxiao.connect.result.BaseApiResult;
import com.baijia.tianxiao.connect.route.api.ClientMessageSendApi;
import com.baijia.tianxiao.connect.route.api.enums.MsgType;
import com.baijia.tianxiao.connect.route.api.model.TianxiaoConnectSession;
import com.baijia.tianxiao.connect.route.api.model.TxMessage;
import com.baijia.tianxiao.connect.service.BizMessageReceiveService;
import com.baijia.tianxiao.connect.util.TianxiaoConnectUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author leiruiqi
 *
 */
@Slf4j
@Service("bizMessageReceiveService")
public class BizMessageReceiveServiceImpl implements BizMessageReceiveService {

	@Resource
	TianxiaoConnectUtil tianxiaoConnectUtil;
	
	//@Resource
	//ExternalInterfaceService externalInterfaceService;
	
	@Resource
	ClientMessageSendApi clientMessageSendApi;
	
	@Override
	public void doExcute(WebSocketSession session, TxMessage txMessage) {
		//解析action对应的bizDomain和bizName
		String action = txMessage.getAction();
		//txMessage.action2BizSign();
		//String bizDomain = txMessage.getBizDomain();
		String bizDomain = null;
		String bizName = null;
		if(StringUtils.isNotBlank(action)){
			String[] actionsplitArray = null;
			try {
				actionsplitArray = action.split("-");
			} catch (Exception e) {
				return;
			}
			if(actionsplitArray!=null&&actionsplitArray.length==2){
				bizDomain = actionsplitArray[0];
				bizName  =actionsplitArray[1];
			}
		}
		
		if(StringUtils.isBlank(bizDomain)){
			String errorMsg = TianxiaoConnectUtil.buildTxMessageErr("","msg action="+txMessage.getAction()+" not suport");
			TextMessage returnmessage = new TextMessage(errorMsg);
			TianxiaoConnectUtil.sendMessage(session, returnmessage);
			return;
		}
		
		if(StringUtils.equals(bizDomain, MessageBizDomain.cc.name())){
			
			doCCBizExcute(session,bizName,txMessage);
		}else{
			
			doBizRoute(session,txMessage);
			
		}
	}
	
	private void doBizRoute(WebSocketSession session, TxMessage txMessage){
		TianxiaoConnectSession txConnectSession = tianxiaoConnectUtil.createTianxiaoSessionCacheModel(session);
		log.info("txMessage info is:"+JSON.toJSONString(txMessage));
		clientMessageSendApi.sendMessage(txConnectSession, txMessage);
	}
	
	private void doCCBizExcute(WebSocketSession session, String bizName,TxMessage txMessage){
		// 暂时无cc相关业务消息
		String errorMsg = TianxiaoConnectUtil.buildTxMessageErr("",
				"msg action=" + txMessage.getAction() + " not suport");
		TextMessage returnmessage = new TextMessage(errorMsg);
		TianxiaoConnectUtil.sendMessage(session, returnmessage);

	}
	
	private void doAddAttributeToCRSession(WebSocketSession session,TxMessage txMessage){
		
		
		String dataStr = txMessage.getData();
		
		//JSON.parseObject(dataStr, Map.class);
		
		JSONObject jsono = JSON.parseObject(dataStr);
		if(jsono ==null || jsono.isEmpty()){
			return;
		}
		
		
		Map<String,Object> extents = (Map<String,Object>)session.getAttributes().get(Constants.EXTENTS_ATTRIBUTE);
		if(extents == null){
			extents = new HashMap<String,Object>();
			session.getAttributes().put(Constants.EXTENTS_ATTRIBUTE, extents);
		}
		
		for(Map.Entry<String, Object> entry:jsono.entrySet()){
			extents.put(entry.getKey(), entry.getValue());
		}
		
		tianxiaoConnectUtil.addBindSessionAttribute(session);
	}
	
	/*private void doAddAttributeToPushPlatform(WebSocketSession session,TxMessage txMessage){
		Map<String,Object> dataMap = null;
		BaseApiResult result = null ;
		try {
			dataMap = JSON.parseObject(txMessage.getData(), Map.class);
			TianxiaoConnectSession txConnectSession = tianxiaoConnectUtil.createTianxiaoSessionCacheModel(session);
			result = externalInterfaceService.pushAddAttribute(txConnectSession.getBizType(), txConnectSession.getUserId(), txConnectSession.getDeviceId(), dataMap);
			
		} catch (Exception e) {
			log.error("doAddAttributeToPushPlatform exception",e);
			result = new  BaseApiResult();
			result.setCode("0");
			result.setMsg("doAddAttributeToPushPlatform exception");
		}
		
		doArkForAddAttributeToPushPlatform(session,result);
		
	}*/
	
	private void doArkForAddAttributeToPushPlatform(WebSocketSession session,BaseApiResult result){
		TxMessage txMessage = new TxMessage();
		txMessage.setType(MsgType.bizArk.name());
		txMessage.setAction(MessageBizDomain.cc.name()+"-"+CCBizName.addAttribute.name());
		txMessage.setData(JSON.toJSONString(result));
	}
	

	public static void main(String[] args) {
		
		JSONObject data = new JSONObject();
		data.put("assignStatus", 1);
		JSONObject object = new JSONObject();
		object.put("type", "biz");
		object.put("action", "cc-addAttribute");
		
		object.put("data",data.toJSONString() );
		
		System.out.println(object.toJSONString());
	}
}
